package com.bfxy.kafka.api.interceptor;

import org.apache.kafka.clients.producer.ProducerInterceptor;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.Map;

public class CustomProducerInterceptor implements ProducerInterceptor<String, String> {

    private volatile long success = 0;

    private volatile long failure = 0;

    /**
     * 发送消息之前的切面拦截
     * @param producerRecord
     * @return
     */
    @Override
    public ProducerRecord<String, String> onSend(ProducerRecord<String, String> producerRecord) {
        System.out.println("--------------- 生产者发送消息前置拦截器 ----------------");
        String modifyValue = "prefix-" + producerRecord.value();
        return new ProducerRecord<>(producerRecord.topic(),
                producerRecord.partition(),
                producerRecord.timestamp(),
                producerRecord.key(),
                modifyValue,
                producerRecord.headers());
    }

    /**
     * 发送消息之后的切面拦截
     * @param recordMetadata
     * @param e
     */
    @Override
    public void onAcknowledgement(RecordMetadata recordMetadata, Exception e) {
        System.out.println("--------------- 生产者发送消息后置拦截器 ----------------");
        if (null == e) {
            success ++;
        } else {
            failure ++;
        }
    }

    @Override
    public void close() {
        double successRatio = (double) success / (success + failure);
        System.out.println(String.format("生产者关闭，发送消息的成功率为：%s %%", successRatio * 100));
    }

    @Override
    public void configure(Map<String, ?> map) {

    }

}
